package com.qian.api.ddj.util;

import com.alibaba.fastjson.JSONObject;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

import javax.servlet.http.HttpServletRequest;
import java.io.*;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLDecoder;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

public class HttpRequestUtil {

    /**
     * ��ָ�� URL ����POST����������
     *
     * @param url
     *            ��������� URL
     * @param param
     *            ����������������Ӧ���� name1=value1&name2=value2 ����ʽ��
     * @return ������Զ����Դ����Ӧ���
     */

    /*
     * POST /webservice.asmx/mdsmssend HTTP/1.1 Host: sdk.entinfo.cn
     * Content-Type: application/x-www-form-urlencoded Content-Length: length
     *
     * sn=string&pwd=string&mobile=string&content=string&ext=string&stime=string
     * &rrid=string&msgfmt=string
     */

    public static String sendPost(String url, String param) {
        PrintWriter out = null;
        BufferedReader in = null;
        StringBuilder result = new StringBuilder();
        try {
            URL realUrl = new URL(url);
            // ���β������ε�SSL��������
            // SslUtil.ignoreSsl();
            // ����ͨ�ô���
            // System.setProperty("http.proxyHost",
            // "myProxyServer.com");System.setProperty("http.proxyPort", "80");
            // �򿪺�URL֮�������
            URLConnection conn = realUrl.openConnection();
            // ����ͨ�õ���������
            conn.setRequestProperty("Content-type", "application/x-www-form-urlencoded");
            conn.setRequestProperty("accept", "*/*");
            conn.setRequestProperty("connection", "Keep-Alive");
            conn.setRequestProperty("Charset", "UTF-8");
            conn.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 5.0; Windows NT; DigExt)");
            // ����POST��������
            conn.setDoOutput(true);
            conn.setDoInput(true);
            // Post ������ʹ�û���
            conn.setUseCaches(false);
            // �������ӳ�ʱ
            conn.setConnectTimeout(600000);
            // ���ö�ȡ��ʱ
            conn.setReadTimeout(600000);
            // ��ȡURLConnection�����Ӧ�������
            out = new PrintWriter(new OutputStreamWriter(conn.getOutputStream(), "UTF-8"));
            // �����������
            out.print(param);
            // flush������Ļ���
            out.flush();
            // ����BufferedReader����������ȡURL����Ӧ
            in = new BufferedReader(new InputStreamReader(conn.getInputStream(), "UTF-8"));
            String line;
            while ((line = in.readLine()) != null) {
                result.append(line);
            }
            // System.out.println(result.toString());
        } catch (Exception e) {
            e.printStackTrace();
            System.out.println("���� POST ��������쳣��");
            result.append("{\"respCode\":\"01\",\"message\":\"���Žӿ�ͨѶ�쳣��\"}");
        }
        // ʹ��finally�����ر��������������
        finally {
            try {
                if (out != null) {
                    out.close();
                }
                if (in != null) {
                    in.close();
                }
            } catch (Exception ex) {
                ex.printStackTrace();
            }
        }
        System.out.println("***********************" + result);
        return result.toString();
    }

    /**
     * ���ɲ���
     *
     * @param params
     * @return
     */
    public static StringBuilder buildParam(Map<String, Object> params) {
        StringBuilder strParam = new StringBuilder();
        for (String key : params.keySet()) {
            strParam.append(key).append("=").append(params.get(key)).append("&");
        }
        return strParam;
    }

    /**
     * ��ȡ����request�������key-value
     *
     * @param request
     * @return
     */
    public static Map<String, String> getRequestParams(HttpServletRequest request) {

        Map<String, String> params = new HashMap<String, String>();
        if (null != request) {
            Set<String> paramsKey = request.getParameterMap().keySet();
            for (String key : paramsKey) {
                params.put(key, request.getParameter(key));
            }
        }
        return params;
    }

    public static String httpPostSendReceive(String url, String jsonString) throws IOException {
        return httpPostSendReceiveWithType(url, jsonString, "text/plain;charset=UTF-8");
    }

    public static String httpPostSendReceiveJson(String url, String jsonString) throws IOException {
        return httpPostSendReceiveWithType(url, jsonString, "application/json;charset=UTF-8");
    }

    public static String httpPostSendReceiveWithType(String url, String jsonString, String contentType)
            throws IOException {

        CloseableHttpResponse response = null;
        CloseableHttpClient client = null;
        String res = null;

        try {
        	System.out.println("����url��" + url);
            HttpPost httpPost = new HttpPost(url);
            StringEntity entityParams = new StringEntity(jsonString, "UTF-8");
            System.out.println("��������" + new String(EntityUtils.toByteArray(entityParams), "UTF-8"));
            httpPost.setEntity(entityParams);
            httpPost.setHeader("Content-Type", contentType);
            httpPost.setHeader("dataType","json");
            client = HttpClients.createDefault();
            response = client.execute(httpPost);
            HttpEntity httpEntity = response.getEntity();

            if (response == null || httpEntity == null) {
                res = "����ʧ��";
                return "";
            }
            res = new String(EntityUtils.toByteArray(httpEntity), "UTF-8");
            System.out.println("��������" + res);

        } catch (Exception e) {
            e.printStackTrace();
            System.out.println(e.getMessage());
            return "";
        } finally {
            if (response != null) {
                response.close();
            }
            if (client != null) {
                client.close();
            }
        }
        return res;
    }

    /**
     * httpPost
     *
     * @param url
     *            ·��
     * @param jsonParam
     *            ����
     * @return
     */
    public static JSONObject httpPost(String url, JSONObject jsonParam) {
        return httpPost(url, jsonParam, false);
    }

    public static JSONObject httpPost(String url, String jsonParam) {
        return httpPost(url, JSONObject.parseObject(jsonParam), false);
    }

    public static String httpPost(String url,  List<NameValuePair> nvps) {
        // post���󷵻ؽ��

        CloseableHttpClient httpClient = HttpClientBuilder.create().build();
        // JSONObject jsonResult = null;
        HttpPost method = new HttpPost(url);
        try {
            method.setEntity(new UrlEncodedFormEntity(nvps));
            HttpResponse result = httpClient.execute(method);
            url = URLDecoder.decode(url, "UTF-8");
            /** �����ͳɹ������õ���Ӧ **/
            if (result.getStatusLine().getStatusCode() == 200) {
                try {
                    /** ��ȡ���������ع�����json�ַ������� **/
                    return EntityUtils.toString(result.getEntity());
                } catch (Exception e) {
                    e.printStackTrace();
                    System.out.println("post�����ύʧ��:" + url);
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
            System.out.println("post�����ύʧ��:" + url);
        }
        return "";
    }
    /**
     * post����
     *
     * @param url
     *            url��ַ
     * @param jsonParam
     *            ����
     * @param noNeedResponse
     *            ����Ҫ���ؽ��
     * @return
     */
    public static JSONObject httpPost(String url, JSONObject jsonParam, boolean noNeedResponse) {
        // post���󷵻ؽ��

        CloseableHttpClient httpClient = HttpClientBuilder.create().build();
        JSONObject jsonResult = null;
        HttpPost method = new HttpPost(url);
        try {
            if (null != jsonParam) {
                // ���������������
                StringEntity entity = new StringEntity(jsonParam.toString(), "utf-8");
                entity.setContentEncoding("UTF-8");
                entity.setContentType("application/json");
                method.setEntity(entity);
            }
            HttpResponse result = httpClient.execute(method);
            url = URLDecoder.decode(url, "UTF-8");
            /** �����ͳɹ������õ���Ӧ **/
            if (result.getStatusLine().getStatusCode() == 200) {
                String str = "";
                try {
                    /** ��ȡ���������ع�����json�ַ������� **/
                    str = EntityUtils.toString(result.getEntity());
                    if (noNeedResponse) {
                        return null;
                    }
                    /** ��json�ַ���ת����json���� **/
                    jsonResult = JSONObject.parseObject(str);
                } catch (Exception e) {
                    e.printStackTrace();
                    System.out.println("post�����ύʧ��:" + url);
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
            System.out.println("post�����ύʧ��:" + url);
        }
        return jsonResult;
    }

    /**
     * ����get����
     *
     * @param url �����ַ
     * @return
     */
    public static JSONObject httpGetJson(String url) {
        // get���󷵻ؽ��
        JSONObject jsonResult = null;
        CloseableHttpResponse response = null;
        CloseableHttpClient client = null;
        try {
            client = HttpClientBuilder.create().build();
            // ����get����
            HttpGet request = new HttpGet(url);
            response = client.execute(request);

            /** �����ͳɹ������õ���Ӧ **/
            if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
                /** ��ȡ���������ع�����json�ַ������� **/
                String strResult = EntityUtils.toString(response.getEntity());
                /** ��json�ַ���ת����json���� **/
                jsonResult = JSONObject.parseObject(strResult);
                url = URLDecoder.decode(url, "UTF-8");
            } else {
                System.out.println("get�����ύʧ��:" + url);
            }
        } catch (IOException e) {
            e.printStackTrace();
            System.out.println("get�����ύʧ��:" + url);
	    } finally {
	        if (response != null) {
	            try {
					response.close();
				} catch (IOException e) {
				}
	        }
	        if (client != null) {
	            try {
					client.close();
				} catch (IOException e) {
				}
	        }
	    }
        return jsonResult;
    }

    /**
     * ����һ���ֽ���
     * @param url
     * @return
     * @throws IOException
     */
    public static ByteArrayInputStream httpGetSream(String url, String charset) {
        CloseableHttpResponse response = null;
        CloseableHttpClient client = null;
        String res = null;

        try {
            System.out.println("����url��" + url);
            HttpGet httpGet = new HttpGet(url);

            httpGet.setHeader("Content-Type", "text/plain;charset=" + charset);
            client = HttpClients.createDefault();
            response = client.execute(httpGet);
            HttpEntity httpEntity = response.getEntity();

            if (response == null || httpEntity == null) {
                res = "����ʧ��";
                System.out.println(res + ": response == null || httpEntity == null");
                return null;
            }
            int statusCode = response.getStatusLine().getStatusCode();
            if (statusCode != HttpStatus.SC_OK) {
                res = "����ʧ��" + statusCode;
                System.out.println(res + ": response.getStatusLine().getStatusCode() = " + statusCode);
                return null;
            }

            return new ByteArrayInputStream(EntityUtils.toByteArray(httpEntity));
        } catch (Exception e) {
            System.out.println("��������");
            e.printStackTrace();
            return null;
        } finally {
            if (response != null) {
                try {
					response.close();
				} catch (IOException e) {
				}
            }
            if (client != null) {
                try {
					client.close();
				} catch (IOException e) {
				}
            }
        }
    }

    public static String httpGetStr(String url) {
        CloseableHttpResponse response = null;
        CloseableHttpClient client = null;
        String res = null;

        try {
            System.out.println("����url��" + url);
            HttpGet httpGet = new HttpGet(url);

            httpGet.setHeader("Content-Type", "text/plain;charset=UTF-8");
            client = HttpClients.createDefault();
            response = client.execute(httpGet);
            HttpEntity httpEntity = response.getEntity();

            if (response == null || httpEntity == null) {
                res = "����ʧ��";
                System.out.println(res + ": response == null || httpEntity == null");
                return "";
            }
            int statusCode = response.getStatusLine().getStatusCode();
            if (statusCode != HttpStatus.SC_OK) {
                res = "����ʧ��" + statusCode;
                System.out.println(res + ": response.getStatusLine().getStatusCode() = " + statusCode);
                return "";
            }

            res = new String(EntityUtils.toByteArray(httpEntity), "UTF-8");
            System.out.println("��������" + res);
        } catch (Exception e) {
            System.out.println("��������");
            e.printStackTrace();
            return "";
        } finally {
            if (response != null) {
                try {
					response.close();
				} catch (IOException e) {
				}
            }
            if (client != null) {
                try {
					client.close();
				} catch (IOException e) {
				}
            }
        }
        return res;

    }
}